package com.example.sunmiv1.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.scan.InfraredScanActivity;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.activity.CaptureActivity;

import org.json.JSONException;
import org.json.JSONObject;
import org.pay.PayCallback;
import org.pay.PayUtils;
import org.pay.gate.model.PayGateReqDataModel;
import org.pay.gate.model.PayGateReqModel;
import org.pay.gate.model.PayGateRespDataModel;
import org.pay.gate.model.PayGateRespModel;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RefundActivity extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.title_more)
    TextView mTitleMore;
    @BindView(R.id.iv_refund)
    ImageView ivRefund;
    @BindView(R.id.edit_refund)
    EditText editRefund;
    @BindView(R.id.tv_refund_confirm)
    TextView tvRefundConfirm;
    @BindView(R.id.linear_refund_scan)
    LinearLayout linearRefundScan;
    @BindView(R.id.edit_refund_pass)
    EditText editRefundPass;
    @BindView(R.id.refund_refund_off)
    ImageView refundRefundOff;
    @BindView(R.id.edit_refund_codePass)
    EditText editRefundCodePass;
    @BindView(R.id.refund_refund_sure)
    TextView refundRefundSure;
    @BindView(R.id.refund_refund_login)
    TextView refundRefundLogin;
    @BindView(R.id.refund_refundLinear)
    LinearLayout refundRefundLinear;
    private ACache aCache;
    private Context context;
    private Intent intent;
    private static final String TAG = "RefundActivity";
    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_refund);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        ButterKnife.bind(this);
        titleBack.setVisibility(View.VISIBLE);
        titleTitle.setText(context.getResources().getString(R.string.refund_title));
        /*mTitleMore.setText("選擇訂單");
        mTitleMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, CollectRecordActivity.class);
                intent.putExtra(CollectRecordActivity.REFUND_KEY,true);
                startActivityForResult(intent,2022);
            }
        });*/
    }


    @OnClick({R.id.title_back, R.id.iv_refund, R.id.tv_refund_confirm,
            R.id.refund_refund_off, R.id.refund_refundLinear, R.id.refund_refund_sure, R.id.refund_refund_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.iv_refund:
                /*intent = new Intent(context, CaptureActivity.class);
                startActivityForResult(intent, 100);*/

                Intent intent = new Intent(context, InfraredScanActivity.class);
                startActivityForResult(intent, 100);
                break;
            case R.id.tv_refund_confirm:
                if (linearRefundScan.getVisibility() == View.VISIBLE) {
                    if (TextUtils.isEmpty(editRefund.getText().toString().trim())) {
                        Toast.makeText(context, "請掃描或輸入正確的訂單條碼", Toast.LENGTH_SHORT).show();
                    } else {
                        if ("2".equals(aCache.getAsString("userType"))) {
                            Refund();
                        } else {
                            refundRefundLinear.setVisibility(View.VISIBLE);
                        }
                    }
                } else {
                    if (TextUtils.isEmpty(editRefundPass.getText().toString().trim())) {
                        Toast.makeText(context, "請輸入退款權限碼", Toast.LENGTH_SHORT).show();
                    } else {
                        Refund();
                    }
                }
                break;
            case R.id.refund_refund_off:
                editRefundCodePass.setText("");
                editRefundPass.setText("");
                refundRefundLinear.setVisibility(View.GONE);
                break;
            case R.id.refund_refundLinear:
                break;
            case R.id.refund_refund_sure:
                if (editRefundPass.getVisibility() == View.GONE) {
                    if (TextUtils.isEmpty(editRefundCodePass.getText().toString().trim())) {
                        Toast.makeText(context, "請輸入權限碼", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    if (TextUtils.isEmpty(editRefundPass.getText().toString().trim())) {
                        Toast.makeText(context, "請輸入店長登錄賬號", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(editRefundCodePass.getText().toString().trim())) {
                        Toast.makeText(context, "請輸入店長登錄密碼", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                Refund();
                break;
            case R.id.refund_refund_login:
                if (editRefundPass.getVisibility() == View.GONE) {
                    editRefundCodePass.setText("");
                    editRefundPass.setVisibility(View.VISIBLE);
                    refundRefundLogin.setText(R.string.refundTip1);
                    editRefundCodePass.setHint(R.string.refundTip2);
                    editRefundPass.postDelayed(() -> editRefundPass.requestFocus(), 500);
                } else {
                    editRefundCodePass.setText("");
                    editRefundPass.setText("");
                    editRefundPass.setVisibility(View.GONE);
                    refundRefundLogin.setText(R.string.refundTip3);
                    editRefundCodePass.setHint(R.string.refundTip4);
                    editRefundCodePass.postDelayed(() -> editRefundCodePass.requestFocus(), 500);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == 100 && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            editRefund.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
        }
        if (data != null && requestCode == 2022 && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            editRefund.setText(bundle.getString("data"));
        }
    }

    private void Refund() {
       // loadingDialog.show();
        doGetaRefundTask();
    /*    JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchant_id", aCache.getAsString("merchantid"));
            jsonObject.put("store_id", aCache.getAsString("storeid"));
            jsonObject.put("cashier_id", aCache.getAsString("uid"));
            jsonObject.put("out_trade_no", editRefund.getText().toString().trim());
            jsonObject.put("operator_identity_id", aCache.getAsString("uid"));
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            }
            if (editRefundPass.getVisibility() == View.GONE) {
                jsonObject.put("username", "");
                jsonObject.put("refund_code", editRefundCodePass.getText().toString().trim());
            } else {
                jsonObject.put("username", editRefundPass.getText().toString().trim());
                jsonObject.put("refund_code", editRefundCodePass.getText().toString().trim());
            }
            jsonObject = Tools.createParameterCode(jsonObject);

            HttpUtils.post(context, Common.QUICK_REFUND, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            Toast.makeText(context, "退款成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }*/
    }

    private final String MerchantID = "106832111290001";
    /**
     * 這裏需要先查詢訂單，獲取訂單信息，再發起退款
     */
    private void doGetaRefundTask() {
        String billNumber = editRefund.getText().toString();
        int length = billNumber.length();
        if (length < 14) {
            Toast.makeText(context, "請輸入正確的訂單編號", Toast.LENGTH_SHORT).show();
            return;
        }
        loadingDialog.show();
        PayGateReqModel payGateReqModel = new PayGateReqModel();
        payGateReqModel.buildCheckAction();
        payGateReqModel.setData(PayGateReqDataModel.buildCheckDataModel(billNumber));
        payGateReqModel.setShopID(MerchantID);
        new PayUtils().reqPayGateTask(payGateReqModel,new PayCallback() {
            @Override
            protected void onSuccess(PayGateRespModel payRespData) {
                if (payRespData.paySuccess()) {
                    refundTask(payRespData);
                } else {
                    loadingDialog.dismiss();
                    Toast.makeText(context, payRespData.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            protected void onFailure(Exception e) {
                loadingDialog.dismiss();
                Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
            }
        });

    }

    /**
     * @param payRespData
     */
   private  void refundTask(PayGateRespModel payRespData){
       PayGateReqModel payGateReqModel = new PayGateReqModel();
       payGateReqModel.buildRefundAction();
       payGateReqModel.setShopID(MerchantID);
       PayGateRespDataModel dataModel= payRespData.getContent();
       payGateReqModel.buildRefundReqData(dataModel.getOrderNumber(), dataModel.getBillNumber(), dataModel.getLocalDate(), dataModel.getLocalTime());
       new PayUtils().reqPayGateTask(payGateReqModel, new PayCallback() {
           @Override
           protected void onSuccess(PayGateRespModel payRespData) {
               loadingDialog.dismiss();
               if (payRespData.paySuccess()) {
                   Toast.makeText(context, "退款成功", Toast.LENGTH_SHORT).show();
                   finish();
               } else {
                   Toast.makeText(context, payRespData.getMsg(), Toast.LENGTH_SHORT).show();
               }
           }

           @Override
           protected void onFailure(Exception e) {
               loadingDialog.dismiss();
               Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
           }
       });
   }


}
